using B.S.RbacData.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SupplierCustomerManagement.Domain.Entities;
using B.S.RbacData.ErrorCode;
using SupplierCustomerManagement.Write.API.Applications.Commands.suppliercontacts;

namespace SupplierCustomerManagement.Write.API.Applications.CommandHandlters.suppliercontacts
{
    /// <summary>
    /// 删除供应商联系人命令处理器
    /// </summary>
    public class DeleteSupplierContactCommandHandler : IRequestHandler<DeleteSupplierContactCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<SupplierContact> _supplierContactRepository;
        private readonly ILogger<DeleteSupplierContactCommandHandler> _logger;

        public DeleteSupplierContactCommandHandler(
            IBaseRepository<SupplierContact> supplierContactRepository,
            ILogger<DeleteSupplierContactCommandHandler> logger)
        {
            _supplierContactRepository = supplierContactRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理删除供应商联系人命令
        /// </summary>
        /// <param name="request">删除供应商联系人命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult<bool>> Handle(DeleteSupplierContactCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证供应商联系人是否存在
                var existingContact = await _supplierContactRepository.GetAll()
                    .FirstOrDefaultAsync(c => c.Id == request.Id && !c.IsDeleted, cancellationToken);

                if (existingContact == null)
                {
                    return ApiResult<bool>.Error("供应商联系人不存在");
                }

                // 软删除：设置删除标记
                existingContact.IsDeleted = true;
                existingContact.UpdatedTime = DateTime.Now;
                existingContact.UpdatedBy =1;

                // 执行删除操作
                var result = await _supplierContactRepository.UpdateAsync(existingContact);

                if (result > 0)
                {
                    _logger.LogInformation("成功删除供应商联系人，ID: {ContactId}, 供应商ID: {SupplierId}, 联系人: {ContactPerson}", 
                        existingContact.Id, existingContact.SupplierId, existingContact.ContactPerson);
                    
                    return ApiResult<bool>.Success(true, "供应商联系人删除成功");
                }
                else
                {
                    _logger.LogError("删除供应商联系人失败，ID: {ContactId}, 联系人: {ContactPerson}", 
                        request.Id, existingContact.ContactPerson);
                    
                    return ApiResult<bool>.Error("供应商联系人删除失败");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除供应商联系人时发生异常，ID: {ContactId}", request.Id);
                
                return ApiResult<bool>.Error($"删除供应商联系人时发生异常: {ex.Message}");
            }
        }
    }
} 